from flask import Blueprint, render_template, flash, redirect, url_for, request, jsonify
from flask_mail import Message
from app.email import send_mail
from app.extensions import db
from app.forms.main import PublishForm
from flask_login import login_user,current_user,login_required,logout_user
from app.models import Posts, RePosts,PingTexts,HuiTexts

main = Blueprint('main', __name__)

#发帖
# @main.route('/',methods=['GET','POST'])
# def index():
#     form = PublishForm()
#     allposts = Posts.query.all()
#     if form.validate_on_submit():
#         if current_user.is_authenticated:
#             myposts = Posts()
#             myposts.uid = current_user.id
#             myposts.content = form.publish_text.data
#             db.session.add(myposts)
#             return redirect(url_for('main.index'))
#         else:
#             flash('请完成登录后再发表！')
#     return render_template('main/index.html',form=form,allposts=allposts)
# 分页版本1.0
# 首页的重定向配合分页使用
# @main.route('/',methods=['GET','POST'])
# def index():
#     return redirect('/index/1')
#
# # 首页测试分页实现方法
# @main.route('/index/<yema>',methods=['GET','POST'])
# def index_two(yema=1):
#     form = PublishForm()
#     yema = int(yema)
#     allposts = Posts.query.order_by(db.desc(Posts.timestamp)).paginate(yema, 3, error_out=True)
#     page = allposts.page
#     pages = allposts.pages
#     if form.validate_on_submit():
#         if current_user.is_authenticated:
#             myposts = Posts()
#             myposts.uid = current_user.id
#             myposts.content = form.publish_text.data
#             db.session.add(myposts)
#             flash('发表成功！！！')
#             return redirect('/index/1')
#         else:
#             flash('请完成登录后再发表！')
#     return render_template('main/index_two.html', form=form, allposts=allposts,page=page,pages=pages)

# 分页版本2.0
# @main.route('/',methods=['GET','POST'])
# def index():
#     form = PublishForm()
#     if form.validate_on_submit():
#         if current_user.is_authenticated:
#             myposts = Posts()
#             myposts.uid = current_user.id
#             myposts.content = form.publish_text.data
#             db.session.add(myposts)
#             flash('发表成功！！！')
#             return redirect(url_for('main.index'))
#         else:
#             flash('请完成登录后再发表！')
#     # 获取页码，默认为1
#     page = request.args.get('page',1,type=int)
#     pagination = Posts.query.filter_by(rid=0).order_by(db.desc(Posts.timestamp)).paginate(page, 3, error_out=True)
#     posts = pagination.items
#     return render_template('main/index_three.html',form=form,posts=posts,pagination=pagination)

####################################################################
#版本3.0
@main.route('/',methods=['GET','POST'])
def index():
    form = PublishForm()
    if form.validate_on_submit():
        if current_user.is_authenticated:
            myposts = Posts()
            myposts.uid = current_user.id
            myposts.content = form.publish_text.data
            db.session.add(myposts)
            flash('发表成功！！！')
            return redirect(url_for('main.index'))
        else:
            flash('请完成登录后再发表！')
    # 获取页码，默认为1
    page = request.args.get('page',1,type=int)
    # 通过时间排序
    pagination = Posts.query.filter_by(rid=0).order_by(db.desc(Posts.timestamp)).paginate(page, 3, error_out=True)
    posts = pagination.items
    # 可以得到数据，进行检测空值过滤，就可以无刷新回复
    # 必须使用form方法的请求
    if request.form.get('b_user') is None:
        pass
    else:
        '''
        必须要获取评论人名字即当前用户 被评论帖子的id(间接得到该帖子的发帖人) 评论内容
        '''
        if current_user.is_authenticated:
            flash('成功')
        else:
            flash('请登录后在评论！')
        try:
            b_user = request.form.get('b_user') #获取的帖子ID
            newpost = Posts.query.filter_by(id=b_user).first() #获取的帖子对象的ID
            re_text = request.form.get('re_text') #获取评论的内容
            pingtext = PingTexts()     #实例化发表帖子模型的表单
            pingtext.pcontent = str(re_text)  #保存评论内容
            pingtext.puser = str(current_user.username)  #保存并论的作者 在这里应该做一次验证是否有用户登录
            pingtext.p_pid = newpost.id   #存储作为外键的帖子id
            db.session.add(pingtext)  #添加数据操作
            db.session.commit()   #提交并保存数据
        except AttributeError:
            flash('请登录后操作')
    return render_template('main/index_four.html',form=form,posts=posts,pagination=pagination)

# 测试ajax请求
@main.route('/mytest',methods = [ "POST", "GET" ])
def mytest():
    if request.method == "POST":
        first_name = request.form.get( "first_name", "null" )
        last_name = request.form.get( "last_name", "null" )
        print(first_name,last_name)
    return render_template('common/mytest.html')

# 测试发送邮件的模块
@main.route('/mail')
def send():
    # msg = Message(subject='title',recipients=['aeasringnar@163.com'],sender='aeasringnar@163.com')
    # msg.html = '<a href="https://www.baidu.com">激活</a>'
    # msg.body = 'https://www.baidu.com 激活'
    # msg.send()
    # 异步的方法发送邮件，在相应的位置定义了一个函数
    send_mail('aeasringnar_green@163.com','主题','email/activte',username='xiaoming')
    return 'down'
